<!-- 发起任务 -->
<template>
  <div class="originating-task">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="流程名称">
          <el-input v-model="searchForm.processName" placeholder="请输入流程名称" clearable />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.startTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">新增流程</el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">删除流程</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="processCode" label="流程编号" min-width="120" />
      <el-table-column prop="processName" label="流程名称" min-width="150" />
      <el-table-column prop="processType" label="流程类别" min-width="120" />
      <el-table-column prop="processVersion" label="流程版本" min-width="100" />
      <el-table-column prop="submitTime" label="提交时间" min-width="160" />
      <el-table-column prop="status" label="流程状态" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="耗时" min-width="100" />
      <el-table-column prop="currentNode" label="当前节点" min-width="120" />
      <el-table-column prop="handler" label="办理人" min-width="100" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增流程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择流程定义"
      width="70%"
      :close-on-click-modal="false"
      style="margin-left: 300px;"
    >
      <!-- 流程定义搜索 -->
      <div class="process-search">
        <el-input
          v-model="processSearchForm.name"
          placeholder="请输入流程名称"
          clearable
          @input="handleProcessSearch"
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 流程定义表格 -->
      <el-table
        v-loading="processLoading"
        :data="processTableData"
        border
        style="width: 100%; margin-top: 15px"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="name" label="流程名称" />
        <el-table-column label="流程版本">
            <template #default="scope">
                <el-tag type="success">V{{ scope.row.version }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="category" label="流程分类"/>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleSelectProcess(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 流程定义分页 -->
      <div class="pagination-container" style="margin-top: 15px">
        <el-pagination
          v-model:current-page="processPagination.currentPage"
          v-model:page-size="processPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="processPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleProcessSizeChange"
          @current-change="handleProcessCurrentChange"
        />
      </div>
    </el-dialog>

    <!-- 流程发起页面 -->
    <el-dialog
      v-model="startProcessVisible"
      :title="null"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      fullscreen
      class="start-process-dialog"
      style="margin-left: 200px;width: 87%;margin-top: 30px;"
    >
      <start-process
        v-if="startProcessVisible"
        :process-info="selectedProcess"
        @close="handleCloseStartProcess"
        @success="handleStartProcessSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import StartProcess from './start-process.vue'

export default {
  name: 'OriginatingTask',
  components: {
    Search,
    StartProcess
  },
  
  data() {
    return {
      // 搜索表单数据
      searchForm: {
        processName: '',
        startTime: []
      },
      // 表格数据
      loading: false,
      tableData: [],
      selectedRows: [],
      // 分页数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 对话框相关数据
      dialogVisible: false,
      processLoading: false,
      processTableData: [],
      processSearchForm: {
        name: ''
      },
      processPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 流程发起相关数据
      startProcessVisible: false,
      selectedProcess: null
    }
  },
  created(){
    this.handleSearch()
  },
  methods: {
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        '进行中': 'primary',
        '已完成': 'success',
        '已驳回': 'danger',
        '已取消': 'info'
      }
      return statusMap[status] || 'info'
    },

    // 搜索方法
    handleSearch() {
      console.log('搜索条件：', this.searchForm)
      this.loading = true
      this.$get('/getMyTasks', {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }).then(res => {
        this.tableData = res.data
        this.pagination.total = res.total
      }).catch(err => {
        console.log(err)
      }).finally(()=>{
        this.loading = false
      })
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.processName = ''
      this.searchForm.startTime = []
      this.handleSearch()
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 新增流程
    handleAdd() {
      this.dialogVisible = true
      this.getProcessDefinitions()
    },

    // 获取流程定义列表
    getProcessDefinitions() {
      this.processLoading = true
      this.$get('/findAllProcessDefinition', {
        // pageNum: this.processPagination.currentPage,
        // pageSize: this.processPagination.pageSize,
        name: this.processSearchForm.name
      }).then(res => {
        this.processTableData = res.data
        // this.processPagination.total = res.total
      }).catch(err => {
        console.error('获取流程定义失败：', err)
        ElMessage.error('获取流程定义失败')
      }).finally(() => {
        this.processLoading = false
      })
    },

    // 流程定义搜索
    handleProcessSearch() {
      this.processPagination.currentPage = 1
      this.getProcessDefinitions()
    },

    // 选择流程
    handleSelectProcess(row) {
        this.$get('/findFormForProcessDefinition', {
            processDefinitionId: row.id
        }).then(res =>{
            if (res.code == 200) {
                this.selectedProcess = row
                this.startProcessVisible = true
                this.dialogVisible = false
            }else{
                ElMessage.warning('该流程未配置表单，请联系管理员进行确认')
            }
        }).catch(err =>{
            console.log(err);
        })
    },

    // 流程定义分页方法
    handleProcessSizeChange(val) {
      this.processPagination.pageSize = val
      this.getProcessDefinitions()
    },

    handleProcessCurrentChange(val) {
      this.processPagination.currentPage = val
      this.getProcessDefinitions()
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        ElMessage.warning('请选择要删除的流程')
        return
      }
      ElMessageBox.confirm('确认删除选中的流程吗？', '提示', {
        type: 'warning'
      }).then(() => {
        console.log('批量删除：', this.selectedRows)
      })
    },

    // 编辑流程
    handleEdit(row) {
      console.log('编辑流程：', row)
    },

    // 删除流程
    handleDelete(row) {
      ElMessageBox.confirm('确认删除该流程吗？', '提示', {
        type: 'warning'
      }).then(() => {
        console.log('删除流程：', row)
      })
    },

    // 分页方法
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.handleSearch()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.handleSearch()
    },

    // 关闭流程发起页面
    handleCloseStartProcess() {
      ElMessageBox.confirm('确认关闭流程发起页面吗？未保存的数据将会丢失', '提示', {
        type: 'warning'
      }).then(() => {
        this.startProcessVisible = false
        this.selectedProcess = null
      }).catch(() => {})
    },

    // 流程发起成功
    handleStartProcessSuccess() {
      this.startProcessVisible = false
      this.selectedProcess = null
      this.handleSearch() // 刷新列表
    }
  }
}
</script>

<style lang="scss" scoped>
.originating-task {
  padding: 20px;

  .search-area {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
    }

    .operation-buttons {
      margin-left: 20px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .process-search {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  :deep(.start-process-dialog) {
    .el-dialog__header {
      display: none;
    }
    
    .el-dialog__body {
      padding: 0;
      height: 100vh;
    }
  }
}
</style>